package com.example.oj_springboot.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * 统一数据格式处理
 */
@ControllerAdvice // 1
public class ResponseAdvice implements ResponseBodyAdvice {

    // 是否要进行内容重写
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 统一数据格式的封装
        if(body instanceof HashMap){
            return body;
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200); // 返回的大状态
        result.put("data", body);
        return result;
    }
}
